<?php

namespace App\Models;

use App\Kits\Errors\ValidateException;
use App\Kits\Services\LibAuthService;
use App\Kits\Traits\BaseModelTrait;
use App\Kits\Validator\BaseValidator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, BaseModelTrait;
    protected $guarded = [];
    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    public static function loginByPassword(array $data, string $ruleName = 'user')
    {
        BaseValidator::make($data, [
            'username' => 'required',
            'password' => 'required',
        ]);
        /** @var User $user */
        $user = User::where('mobile', $data['username'])->first();
        if (!$user || !Hash::check($data['password'], $user->password)) {
            throw new ValidateException('用户名或密码错误');
        }
//        if (!$user->hasAnyRole($ruleName)) {
//            throw new NotAuthException();
//        }
        $tokenName = "【{$data['username']}】登录";
        $token = LibAuthService::generateTokenByUser($user, $tokenName);
        return [$user, $token];
    }
}
